package com.ruoyi.project.mahjong.controller.api;


import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.interceptor.annotation.RepeatSubmit;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.Result;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.mahjong.domain.*;
import com.ruoyi.project.mahjong.domain.dto.MoneyDto;
import com.ruoyi.project.mahjong.domain.vo.TOpenTableVo;
import com.ruoyi.project.mahjong.mapper.TCostMapper;
import com.ruoyi.project.mahjong.service.*;
import com.ruoyi.project.mahjong.service.impl.TCostServiceImpl;
import com.ruoyi.project.mahjong.service.impl.TRoomServiceImpl;
import com.ruoyi.project.system.domain.SysUser;
import io.swagger.annotations.*;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/mahjong/record")
@Api(tags = "房间和桌子操作api")
public class RoomApiController extends BaseController{
    @Autowired
    private ITRoomService itRoomService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ITTablenumberService tablenumberServicel;
    @Autowired
    private ITOpenTableService openTableService;
    @Autowired
    private TCostServiceImpl tCostService;
    @Autowired
    private ITOpenMoneyService openMoneyService;
    @Autowired
    private ITMemberService memberService;




    @PostMapping("/saveOrUpdateRoom")
    @ApiOperation(value = "新增和修改房间",httpMethod = "POST")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "roomName",value = "房间名称",dataType = "String",required = true)})
    @RepeatSubmit
    public Result<Integer> saveOrUpdateRoom(@RequestBody TRoom room)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());

       if (room.getId()==null){
           boolean check= itRoomService.checkRoom(shopId,room.getRoomName());
           if(!check){
               return Result.error("改店铺已经存在场地类型，不允许重复添加！");
           }

           room.setBak1(shopId.toString());
           int i = itRoomService.insertTRoom(room);
           String s= i==1?"新增成功":"新增失败,请重试";
           return Result.success(s);
       }
        int i = itRoomService.updateTRoom(room);
        String s= i==1?"修改成功":"修改失败,请重试";
        return Result.success(s);
    }

    @PostMapping("/saveTable")
    @ApiOperation(value = "新增和修改桌子",httpMethod = "POST")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "roomType",value = "桌号归属房间id",dataType = "String",required = true),
            @ApiImplicitParam(name = "tablenumberId",value = "桌子名称",dataType = "String",required = true),
    })
    @RepeatSubmit
    public Result<Integer> saveOrUpdateTable(@ApiParam("房间字段描述")@RequestBody TTablenumber tTablenumber)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        if (tTablenumber.getId()==null){
            tTablenumber.setBelong(shopId.toString());
            int i = tablenumberServicel.insertTTablenumber(tTablenumber);
            String s= i==1?"新增成功":"新增失败,请重试";
            return Result.success(s);
        }
        int i = tablenumberServicel.updateTTablenumber(tTablenumber);
        String s= i==1?"修改成功":"修改失败,请重试";
        return Result.success(s);
    }
    @PostMapping("/saveOrUpdateCost")
    @ApiOperation(value = "新增和修改计费规则 传id新增，不传为修改",httpMethod = "POST")
    @RepeatSubmit
    public Result saveOrUpdateCost(@ApiParam("计费实体类字段描述")@RequestBody TCost cost)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
        if (cost.getId()==null){
            cost.setBak2(shopId.toString());
             int i = tCostService.insertTCost(cost);
            return  Result.success(i==1?"新增成功":"新增失败,请重试");
        }

        int i = tCostService.updateTCost(cost);
        return  Result.success(i==1?"修改成功":"修改失败,请重试");
    }
    @GetMapping("/getCost")
    @ApiOperation(value = "查询计费方式列表 ",httpMethod = "GET")
    public Result<TCost> getCost()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
         TCost tCost = new TCost();
        tCost.setBak2(shopId.toString());
        return  Result.success(tCostService.selectTCostList(tCost));
    }
    @GetMapping("/getRoom")
    @ApiOperation(value = "查询房间列表 ",httpMethod = "GET")
    public Result getRoom()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long shopId = redisCache.getCacheObject(Constants.SHOP_SUF + user.getUserId());
         TRoom room = new TRoom();
        room.setBak1(shopId.toString());
        return  Result.success(itRoomService.selectTRoomList(room));
    }

    @GetMapping("/addOpenTableMember/{memberId}/{orderNumber}")
    @ApiOperation(value = "开桌后增加会员信息 ",httpMethod = "GET")
    public Result addOpenTableMember(@PathVariable List<Long> memberId,@PathVariable String orderNumber) {
        for (Long id : memberId) {
            TOpenTable table = new TOpenTable();
            table.setMemberId(String.valueOf(id));
            table.setBak2(orderNumber);
            table.setIsDel("0");
            List<TOpenTable> tOpenTableList = openTableService.selectTOpenTableList(table);
            if(!tOpenTableList.isEmpty()){
                TOpenTable openTable = tOpenTableList.get(0);
                return  Result.error("人员["+openTable.getMemberName()+"]已经存在，不允许添加");
            }
            TMember member = memberService.selectTMemberById(id);
            if(ObjectUtil.isNull(member)){
                return  Result.error("人员信息查询失败！");
            }
            if(member.getTableIng().longValue()!=0L){
                return  Result.error("该人员在其他桌子不允许添加");
            }
            openTableService.addMember(id,orderNumber);
        }
        return  Result.success();
    }
    @GetMapping("/ListOpenMoney")
    @ApiOperation(value = "开桌后的购买的商品列表 ",httpMethod = "GET")
    public TableDataInfo ListOpenMoney(@Validated MoneyDto moneyDto)
    {
        TOpenMoney table=new TOpenMoney();
        table.setMemberId(moneyDto.getMemberId());
        table.setOrderNumber(moneyDto.getOrderNumber());

        startPage();
        List<TOpenMoney> openMoneyList=openMoneyService.selectTOpenMoneyList(table);
        return getDataTable(openMoneyList);
    }

    @GetMapping("/listOpenAllMoney")
    @ApiOperation(value = "开桌后的购买的商品列表 ",httpMethod = "GET")
    public Result listOpenAllMoney(@Validated MoneyDto moneyDto)
    {
        TOpenMoney table=new TOpenMoney();
        table.setMemberId(moneyDto.getMemberId());
        table.setOrderNumber(moneyDto.getOrderNumber());
        List<TOpenMoney> openMoneyList=openMoneyService.selectTOpenMoneyList(table);
        Double commitdyMoney=  openMoneyList.stream().mapToDouble(person -> person.getMoney().doubleValue()).sum();
        Map<String,Object> tt=new HashMap<>();
        tt.put("dataList",openMoneyList);
        int roundedNum = (int) Math.round(commitdyMoney);
        tt.put("money",roundedNum);

        return Result.success(tt);
    }

}
